# -*- codeing = utf-8 -*-
# @Time : 2022/8/6 12:59
# @Author : ZN
# @Email : 747723508@qq.com
# @File : verifyUtil.py
# @Software: PyCharm
import os
import random
import string
from PIL import Image, ImageFont, ImageDraw, ImageFilter
from django_redis import get_redis_connection

from config.dbs.redis_dev import LOGIN_KEY_TEMPLATE


class ImageVerify:
    def __init__(self, x=140, y=40, length=4, size=28):
        """
                初始化
                :param x: 图片的X轴，宽度
                :param y: 图片的y轴，长度
                :param length: 字符的个数，长度
                :param size: 字符的大小
                """
        self.x = x
        self.y = y
        self.length = length
        self.size = size

    def random_str(self):
        """
                随机生成指定长度的字符串
                数据源：26个字母+10个数字
                :return: 生成的随机字符串
                """
        source = string.ascii_letters + string.digits
        return ''.join(random.sample(source, self.length))

    def random_color(self, start=0, end=255):
        """
                随机生成颜色，一张有颜色的栅格图是三维数据
                [
                [(1,2,3),(1,2,1)],
                [(1,2,3),(1,2,1)]
                ]
                :param start: 颜色范围的最小值，起始值
                :param end: 颜色方位的最大值，结束值
                :return: tuple (r,g,b) 0-255
                """
        res = [random.randint(start, end) for i in range(3)]
        return tuple(res)

    def random_lines(self, draw):
        """
                绘制干扰线
                :param draw: draw对象 画笔
                :return:
                """
        for i in range(self.length):
            lines = [(random.randint(0, self.x), random.randint(0, self.y)) for i in range(2)]
            draw.line(lines, fill=self.random_color(64, 200))

    def random_points(self, draw, rate):
        """
                绘制干扰点
                :param draw: draw对象 画笔
                :param rate: 频率，干扰点的出现频率
                :return:
                """
        for x in range(self.x):
            for y in range(self.y):
                if random.randint(1, 100) <= rate:
                    draw.point((x, y), fill=self.random_color(64, 200))

    def verify_code(self):
        '''
        生成验证码图片
        :return: 图片，正确答案
        '''
        # 创建Image对象，创建画布
        image = Image.new('RGB', (self.x, self.y), (255, 255, 255))
        # 创建Font对象 字体
        file = os.path.dirname(os.path.abspath(__file__))  # 字体文件
        font = ImageFont.truetype(f'{file}/HYYakuHei-85W.ttf', self.size)
        # 创建Draw 画笔，绘制图形，点，线
        draw = ImageDraw.Draw(image)

        # 绘制干扰点，干扰线
        self.random_lines(draw)
        self.random_points(draw, 15)

        # 调用随机生成字符方法，验证码值
        code = self.random_str()

        # 使用画笔将Font类型的字体对应的字符内容和颜色绘制
        for i in range(self.length):
            draw.text((35 * i + 5, 3), code[i], font=font, fill=self.random_color(32, 127))

        # 模糊滤镜
        image = image.filter(ImageFilter.BLUR)
        return image, code


def jwt_token(token, user=None, request=None):
    """
    自定义登陆成功后的响应函数，登陆后的数据处理函数
    执行这个函数，账号和密码肯定是正确有效的了，手动校验验证码即可
    :param token: 令牌
    :param user: 登陆的用户
    :param request: 请求对象
    :return: 登陆接口响应的内容，token
    """
    param = request.data
    uuid = param.get('uuid')
    verify = param.get('verify')

    if not uuid or not verify:
        return {'msg': '请输入验证码'}

    # 得到redis保存的该客户端的验证码答案与他传入过来的结果进行判断
    cache = get_redis_connection(alias='verify_codes')
    redis_verify = cache.get(LOGIN_KEY_TEMPLATE % uuid)
    cache.delete(LOGIN_KEY_TEMPLATE % uuid)
    if not redis_verify:
        return {'msg': '验证码过期'}

    if redis_verify.upper() != verify.upper():
        return {'msg': '验证码错误'}

    return {
        'token': token,
        'id': user.id,
        'username': user.username,
        'avatar': user.userdetail.avatar if hasattr(user, 'userdetail') else None
    }


if __name__ == '__main__':
    imgVerify = ImageVerify()
    img, code = imgVerify.verify_code()
    with open('test.png', 'wb') as fp:
        img.save(fp)
    print(code)
